from aalpy.learning_algs import run_Lstar
import sys
from pesp4.IKESUL import *
import DBhelper
import utils
from learning.Errors import NonDeterministicError



def ju_run_Lstar(alphabet: list, sul, eq_oracle, automaton_type,db_path,max_query = 5, samples=None,
              closing_strategy='shortest_first', cex_processing='rs',
              e_set_suffix_closed=False, all_prefixes_in_obs_table=True,
              max_learning_rounds=None, cache_and_non_det_check=True, return_data=False, print_level=2):
    
    while True:
        try:
            learned_model = run_Lstar(alphabet, sul, eq_oracle, automaton_type='mealy', cache_and_non_det_check=False, print_level=3)
            return learned_model
        except NonDeterministicError as e:
            print(f"\033[31m{'#'*80}\033[0m")
            print('try to find most common respose')
            querys = e.querys
            most_common_respose = utils.get_most_respose(sul,querys,max_query)
            print(querys)
            print(most_common_respose)
            print('try to delete wrong respose in db')
            db = DBhelper.DBhelper(db_path)
            db.clean_db(querys,most_common_respose)
            print('try to clean cache tree')
            sul.clean_cacheTree()
            print(f"\033[31m{'#'*80}\033[0m")
            # sys.exit()
        
        except Exception as e:
            print(e)
            break
    

